﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using CoreEx.Common.Extensions;
using CoreEx.Database.Metadata.Generation;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;
namespace CoreEx.Database.MetaData.Implementation.Generation
{
    [Implements(typeof(ITypeWriter))]
    public class TypeWriter : ITypeWriter, IInitialize  
    {

        public IFieldWriter FieldWriter { get; set; }
        
        
        public void Write(TypeDescription typeDescription, TextWriter textWriter)
        {
            WriteNamespaceReferences(typeDescription, textWriter);
            WriteNameSpace(typeDescription, textWriter);
        }


        protected virtual void WriteNamespaceReferences(TypeDescription typeDescription, TextWriter textWriter)
        {
            typeDescription.References.ForEach(nsr => WriteNamespaceReference(nsr, textWriter));
        }

        protected virtual void WriteNamespaceReference(string namespaceReference, TextWriter textWriter)
        {
            textWriter.WriteLine(0, "using {0};", namespaceReference);  
        }


        protected virtual void WriteNameSpace(TypeDescription typeDescription, TextWriter textWriter)
        {
            textWriter.WriteLine(0, "namespace {0}", typeDescription.Namespace);
        }

        protected virtual void WriteTypeDeclaration(TypeDescription typeDescription, TextWriter textWriter)
        {
            

        }

        protected virtual void WriteFields(TypeDescription typeDescription, TextWriter textWriter)
        {
            FieldWriter.WriteFields(typeDescription.Properties);
        }


        public void Initialize(IServiceContainer source)
        {
            FieldWriter = source.GetService<IFieldWriter>();
        }
    }
}
